//加密
#include <stdio.h>  
#include <string.h>  
#include <stdlib.h>  
#include <gmssl/sm2.h>  
#include <gmssl/sm3.h>  
#include <gmssl/error.h>  

// 辅助函数：以十六进制格式打印字节数组  
void print_hex(const char *label, const uint8_t *data, size_t len) {  
    printf("%s: ", label);  
    for(size_t i = 0; i < len; i++) {  
        printf("%02X", data[i]);  
    }  
    printf("\n");  
}  
void duqu(char *filename, char **in, size_t *len) {

	FILE *file = fopen(filename, "rb");
	if (!file) {
		perror("Failed to open file");
		return;
	}

	fseek(file, 0, SEEK_END);
	*len = ftell(file);
	fseek(file, 0, SEEK_SET);

	*in = (char *)calloc(*len, 1);

	if (!*in) {
		perror("Failed to allocate memory");
		fclose(file);
		return;
	}

	fread(*in, 1, *len, file);
	fclose(file);
}

void xieru(char *filename, uint8_t *out, size_t *len) {

	FILE *file = fopen(filename, "wb");
	if (!file) {
		perror("Failed to open file");
		return;
	}

	fwrite(out, sizeof(uint8_t), *len, file);
	fclose(file);
}
int duqu_p(char *filename,SM2_KEY* mykey)
{
	FILE *file;  
     
   // 打开文件以读取  
    file = fopen(filename, "rb");  

    if (file == NULL) {  
        perror("Error opening file for writing");  
        return 1;  
    }  
  
	fread(&(mykey->public_key), sizeof(SM2_Z256_POINT), 1, file);

    // 写入字符串到文件  
    fclose(file); // 关闭文件 
    return 0;
}



int duqu_s(char *filename,SM2_KEY* mykey)
{
	FILE *file;  
     
   // 打开文件以读取  
    file = fopen(filename, "rb");  

    if (file == NULL) {  
        perror("Error opening file for writing");  
        return 1;  
    }  
	fread(mykey, sizeof(SM2_KEY), 1, file);

     
    fclose(file);  
    return 0;
}



int main(int argc, char *argv[]){
	if(argc<3){
	printf("no enough filename\n");
	return 0;
	}
	
	
	
    int ret = 0;  



	SM2_KEY key;
	duqu_p(argv[1],&key);
	
	char *plaintext;
	size_t plaintext_len;
    duqu(argv[2], &plaintext, &plaintext_len);

    
    printf("明文: %s\n", plaintext);  

    // 3. 加密明文  
    uint8_t ciphertext[SM2_MAX_CIPHERTEXT_SIZE];  
    size_t ciphertext_len = sizeof(ciphertext);  

    printf("加密明文...\n");  
    ret = sm2_encrypt(&key, (const uint8_t *)plaintext, plaintext_len, ciphertext, &ciphertext_len);  
    if (ret != 1) {  
        fprintf(stderr, "SM2 加密失败\n");  
        return EXIT_FAILURE;  
    }  
    printf("加密成功。\n");  

    // 打印密文  
    xieru(argv[3], ciphertext, &ciphertext_len);

    return EXIT_SUCCESS;  
}
